package cn.hengzhu.main_manager.utils.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;


/**
 * 1 自定义一个过滤器
 *
 */
public class ManagerPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
		  Subject subject = getSubject(request, response);
	        if (subject.getPrincipal() == null) {
	            saveRequestAndRedirectToLogin(request, response);
	        } else {
	        	HttpServletRequest httpServletRequest = (HttpServletRequest) request;
	        	HttpServletResponse httpServletResponse = (HttpServletResponse) response;
	        	//区分是否是Ajax
	        	String xRequestedWith = httpServletRequest.getHeader("X-Requested-With");
	        	if (StringUtils.hasText(xRequestedWith)&&"XMLHttpRequest".equals(xRequestedWith)) {
	        		//否则返回没有权限的Json {"success":false,"message":"对不起,你没有权限访问!"}
	        		httpServletResponse.setContentType("text/json; charset=UTF-8");
	        		httpServletResponse.getWriter().write("{\"success\":false,\"message\":\"对不起,你没有权限,若需要开通请联系管理员!\"}");
				}else{
					//如果不是走原来得逻辑
		            String unauthorizedUrl = getUnauthorizedUrl();
		            if (StringUtils.hasText(unauthorizedUrl)) {
		                WebUtils.issueRedirect(request, response, unauthorizedUrl);
		            } else {
		                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
		            }
				}
	        	
	        }
	        return false;
	}
	
	
	

}
